﻿using System;
using Sync.Properties;
using ToodleDo;
using Folders = Sync.Outlook.OutlookCategories;


namespace Sync
{
    public class Syncer
    {
        

        #region members
       
        
        public bool Ok {get{return Remote.Session != null;}}

        private FolderSync _foldersync;
        private TaskSync _tasksync;

        #endregion

        #region Constructors & Init

        public Syncer(string userid, string password)
        {            
            //_store = IsolatedStorageFile.GetUserStoreForApplication();
            Remote.Init(userid,password,Settings.Default.AppId, Settings.Default.AppToken);                        
            _foldersync = new FolderSync();
            _tasksync = new TaskSync();            
        }

        

        #endregion

        #region Public Methods
        public void Sync()
        {
            try
            {
                SyncFolders();
                SyncTasks();            
            }
            catch (Exception e)
            {
                Logger.InvokeMessageEvent(e.Message,Logger.MessageType.Error);                
            }      
            
        }

       

        public void SyncTasks()
        {
            TaskSync.Sync();
            SyncSessionWrapper.Save();            
        }

        public void SyncFolders()
        {
            DateTime lastfolderedit = Remote.Session.Account.LastFolderEdit;
            DateTime lastSync = SyncSessionWrapper.SyncSession.LastSyncUtc;
            bool hashmatch = SyncSessionWrapper.SyncSession.CategoryHash == SyncSession.CalculateCategoryHash(Folders.All);
            if (lastfolderedit > lastSync || !hashmatch)
            {                
                _foldersync.Sync();
                SyncSessionWrapper.SyncSession.CategoryHash = SyncSession.CalculateCategoryHash(Folders.All);
                Logger.InvokeMessageEvent("Folders Synced",Logger.MessageType.Tracking);
            }
            
        }

        

        #endregion

        #region Private Methods

        

       

        
        
         

        #endregion
    }
}
